package com.fjwt.gz.province.henan;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.third.bo.RealnameBo;
import com.fjwt.gz.core.third.interfaces.RealNameAuthInterface;
import com.fjwt.gz.zhyx.AESUtils;
import com.fjwt.gz.zhyx.SignUtils;
import com.fjwt.gz.zhyx.ZhyxKit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
public class HenanRealNameAuthService extends RealNameAuthInterface {

    @Value("${isFormal.code}")
    private boolean isFormalCode;
    /**
     * 调用智慧营销2.0接口实名认证接口
     **/
    @Override
    @Transactional
    public JSONObject realNameAuth(RealnameBo realnameBo) {
        // 引导用户实名所需参数
        log.info("河南实名认证接口进来的请求参数:{}", JSONUtil.toJsonStr(realnameBo));
        if (!realnameBo.getLocationAgentNo().equals("41000122")&&!realnameBo.getLocationAgentNo().equals("22011060")){
            throw new BizException("抱歉,该地区暂不支持实名认证");
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("idCard", realnameBo.getIdCard());
        jsonObject.put("phone", realnameBo.getPhone());
        jsonObject.put("name", realnameBo.getName());
        String realNameAuthUrl = ZhyxKit.REAL_NAME_AUTH_URL;
        if (isFormalCode){
            realNameAuthUrl = ZhyxKit.REAL_NAME_AUTH_URL_FORMAL;
        }
        String encryptStr = AESUtils.getInstance().encrypt(JSONUtil.toJsonStr(jsonObject));
        long timeStamp = System.currentTimeMillis();
        String authSign = SignUtils.getEncryptSign(encryptStr, timeStamp);

        log.info("河南实名认证请求地址：{}, 请求参数：{}, 加密串：{}", realNameAuthUrl, encryptStr, authSign);
        HttpResponse response = HttpRequest.post(realNameAuthUrl)
                .header("Content-Type", MediaType.TEXT_PLAIN_VALUE)
                .header("sign-type", SignUtils.SIGN_TYPE)
                .header("auth-apikey", SignUtils.API_KEY)
                .header("auth-sign", authSign)
                .header("auth-timestamp", String.valueOf(timeStamp))
                .timeout(15000)
                .body(encryptStr)
                .execute();
        log.info("河南实名认证response:{}", JSONUtil.toJsonStr(response));
        String body = response.body();
        log.info("河南实名认证返回的数据是：{}", JSONUtil.toJsonStr(body));
        JSONObject reapJson = JSONObject.parseObject(body);
        //TODO 注意：此刻返回的是所有数据，这里没有对code做任何校验，到上面一层进行处理
        //TODO 上面一层处理时需注意：返回的数据有需要存储到数据库，记得保存数据库，参照老版的
        return reapJson;
    }
}
